class ProjectsController < ApplicationController
  before_filter :login_required

  def index
    @active_projects  = Project.find_all_active
    @archived_projects = Project.find_all_archived

    @activity_logs = ActivityLog.find(:all, :order => 'created_at DESC', :limit => 50)

  end
  
  def new
    @project = Project.new
    @pattern_phases = Array.new
  end

  def edit
    @project = Project.find params[:id]
    @pattern_phases = @project.activities
  end
  
  def create
    @activities = Array.new
    @project = Project.new(params[:project].merge(:is_active => true, :created_by => current_user.id))
    @pattern_id = params[:project_pattern][:id]

    sum = 0

    #check if phases exist and sum phase weights
    if params[:phases][:id].nil?
      flash[:error] = 'No phases were added.'
      render :action => 'new' and return
    end

    #saving user input
    params[:phases][:id].each_with_index do |phase_id,index|
      unless phase_id.empty? or phase_id.nil?
        @activity = Activity.new(:phase_id=>phase_id,:weight=>params[:phases][:weight][index])
      else
        @phase = Phase.new(:name=>params[:phases][:name][index])
        @activity = Activity.new(:weight=>params[:phases][:weight][index])
        @activity.phase = @phase
      end
      @activities.push(@activity)
    end
    @pattern_phases = @activities

    params[:phases][:weight].each do |w|
      if  w.to_i<0
        flash[:error] = 'Phase weights must be equal to or greater than zero!'
        render :action=>'new' and return
      end
      sum += w.to_i
    end

    #check phase sum = 100
    unless sum==100
      flash[:error] = 'Phase weights must sum up to 100%'
      render :action=>'new' and return
    end

    #clear error messages
    flash.clear
    
    #create project
    if @project.save

      @activities.each do |@activity|
        
        #set project_id for activities
        @activity.project_id = @project.id

        #save if new phases are added
        if @activity.phase_id.nil?
          unless @activity.phase.save
            flash[:error] = 'Phase could not be created!'
            render :action=>'new' and return
          else
            @activity.phase_id = @activity.phase.id
          end
        end
      end

      #create patterns if save as new pattern
      if params[:project_pattern][:new].to_i == 1
        @pattern = Pattern.create(:title=>@project.name + ' pattern')
        @activities.each do |@activity|
          @pattern_phase = PatternsPhase.new(:pattern_id=>@pattern.id,:phase_id=>@activity.phase_id,:weight=>@activity.weight)
          @pattern_phase.save
        end if @pattern.save
      end
     
      #creating activities
      @activities.each do |@activity|
        @activity.save
      end

    else
      render :action => 'new' and return
    end

    #assign all users as project members
    @users = User.find :all
    @users.each do |@user|
      MembersProject.create(:project_id=>@project.id,:user_id=>@user.id)
    end unless @users.empty?
    
    flash[:notice] = 'Project successfully created!'
    redirect_to @project

  end

  def update
    @project = Project.find params[:id]
    @activities = Array.new
    @pattern_id = params[:project_pattern][:id]
    sum = 0

    #check if phases exist and sum phase weights
    if params[:phases][:id].nil?
      flash[:error] = 'No phases were added.'
      render :action => 'edit' and return
    end

    #saving user input
    params[:phases][:id].each_with_index do |phase_id,index|
      unless phase_id.empty? or phase_id.nil?
        #get current phase
        @activity = Activity.find(:first,:conditions => [ "phase_id = ? and project_id=?",
            phase_id,@project.id])
        @activity.weight = params[:phases][:weight][index]
      else
        @phase = Phase.new(:name=>params[:phases][:name][index])
        @activity = Activity.new(:weight=>params[:phases][:weight][index])
        @activity.phase = @phase
      end
      @activities.push(@activity)
    end
    @pattern_phases = @activities

    params[:phases][:weight].each do |w|
      if  w.to_i<0
        flash[:error] = 'Phase weights must be equal to or greater than zero!'
        render :action=>'edit' and return
      end
      sum += w.to_i
    end

    #check phase sum = 100
    unless sum==100
      flash[:error] = 'Phase weights must sum up to 100%'
      render :action=>'edit' and return
    end

    #if there are money collections for this project prevent currency from being deleted.
    if params[:project][:currency]!=@project.currency and @project.collection_amount_total(true)>0
      flash[:error] = "#{@project.collection_amount_total} #{@project.currency}
is collected for this project, you can't change project currency!"
    end

    #any phases deleted?
    if @project.activities.length>@activities.length
      @project.activities.each do |actvty|

        
        if !@activities.include?(actvty)

          #check if workunits were entered for this phase
          if actvty.total_working_hours>0
            flash[:error] = "There are #{actvty.total_working_hours} hours worked for #{actvty.phase.name}, you can't delete this phase !"
            @pattern_phases = @project.activities
            render :action=>'edit' and return

            #check if any money was collected
          elsif actvty.collection_amount_total(true)>0
            flash[:error] = "#{actvty.collection_amount_total(true)} #{@project.currency} is collected from customer for #{actvty.phase.name}, you can't delete this phase !"
            @pattern_phases = @project.activities
            render :action=>'edit' and return

            #if no problem, then remove phase
          else 
            actvty.destroy
          end
        end
      end
    end

    #clear error messages
    flash.clear

    #update project
    if @project.update_attributes(params[:project])
      @activities.each do |activity|

        #set project_id for activities
        activity.project_id = @project.id

        #save if new phases are added
        if activity.phase_id.nil?
          unless activity.phase.save
            flash[:error] = 'Phase could not be created!'
            render :action=>'edit' and return
          else
            activity.phase_id = activity.phase.id
          end
        end
      end

      #create patterns if save as new pattern
      if params[:project_pattern][:new].to_i == 1
        @pattern = Pattern.create(:title=>@project.name + ' pattern')
        @activities.each do |@activity|
          @pattern_phase = PatternsPhase.new(:pattern_id=>@pattern.id,:phase_id=>@activity.phase_id,:weight=>@activity.weight)
          @pattern_phase.save
        end if @pattern.save
      end

      #creating activities
      @activities.each do |activity|
        #update current phase with new details
        activity.save
      end

    else
      render :action => 'edit' and return
    end

    flash[:notice] = 'Project successfully updated!'
    redirect_to @project and return
  end
  
  def show
    @project = Project.find_by_id(params[:id])
    @description = @project.description
    @task_ids = @project.tasks.collect{|task| task.id}
    @activity_logs = ActivityLog.find(:all, :conditions => ['task_id IN (?)', 
        @task_ids], :order => 'created_at DESC', :limit => 50 ) unless @task_ids.nil?
    @activities = @project.activities
    @activity = Activity.find_by_id(params[:id])
    
    @task = Task.find_by_id(params[:id])
    #     @workunits=@task.workunits
    #     @activity_task_ids = @activity.tasks.collect{|task| task.id}
    @phases = []
    for activity in @activities
      @phases << Phase.find_by_id(activity.phase_id)
    end
    #     @working_hours = @workunits.collect { |time| time.amount.to_i}.sum
    #     @estimated_hours = @activities.collect { |phase| phase.projected_time.to_i}.sum
    #     @total_cost = @workunits.collect { |a| a.cost.to_i}.sum
    @total_working_hours = Workunit.sum(:amount, :conditions => ['task_id = ?', params[:id]])
  end
end